/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ac.pbp.controller;

import ac.pbp.core.exception.DataAdditionException;
import ac.pbp.core.exception.DataDeletionException;
import ac.pbp.core.exception.DataModificationException;
import ac.pbp.core.exception.ServiceException;
import ac.pbp.model.Buku;
import ac.pbp.service.BukuService;
import ac.pbp.core.util.ViewHelper;
import ac.pbp.dto.BukuDto;
import ac.pbp.dto.filter.BukuFilterCriteria;
import ac.pbp.model.BukuUser;
import ac.pbp.model.User;
import ac.pbp.service.PengarangService;
import ac.pbp.service.UserService;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.catalina.util.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

/**
 *
 * @author Kim
 */
@Controller
public class BukuController {

    @Autowired
    private BukuService bukuService;
    @Autowired
    private UserService userService;
    @Autowired
    private PengarangService pengarangService;

    @RequestMapping("/bukuView.html")
    public ModelAndView viewBuku(HttpServletRequest request) {

        String page = request.getParameter("page");
        String mode = request.getParameter("mode");

        if ((page == null) || page.equals("")) {
            page = "1";
        }

        BukuFilterCriteria filter = new BukuFilterCriteria();
        filter.setPage(Integer.valueOf(page));
        filter.setMax(100);

        String dataSearch = null;
        if (mode != null) {
            if (mode.equals("search")) {
                dataSearch = request.getParameter("dataSearch");
                if (!dataSearch.equals("")) {
                    filter.setDataSearch(dataSearch);
                }
            }
        }

        BukuDto bukuDto = bukuService.filterBuku(filter);

        ModelAndView model = new ModelAndView("bukuView");
        model.addObject("data", bukuDto);
        //model.addObject("dataSearch", dataSearch);

        return model;
    }

    @RequestMapping("/bukuPrepareAdd.html")
    public ModelAndView prepareAddBuku(HttpServletRequest request) {

        ModelAndView model = new ModelAndView("bukuAdd");

        model.addObject("pengarangList", pengarangService.loadAll());

        return model;
    }

    @RequestMapping(value = "/bukuAdd.html", method = RequestMethod.POST)
    public ModelAndView addBuku(@ModelAttribute("buku") Buku buku, @RequestParam("kodePengarang") String kodePengarang,
            @RequestParam("fileGambar") MultipartFile fileGambar, HttpServletRequest request, HttpServletResponse response)
            throws ServiceException, IOException, IllegalStateException, ServletException {

        String cover = Base64.encode(fileGambar.getBytes());

        bukuService.addBuku(buku, kodePengarang, cover);


        return ViewHelper.redirectTo("bukuView.html");
    }

    @RequestMapping("/bukuPrepareUpdate.html")
    public ModelAndView prepareUpdateBuku(HttpServletRequest request) {

        String kodeBuku = request.getParameter("kodeBuku");

        ModelAndView model = new ModelAndView("bukuAdd");
        Buku buku = bukuService.loadBuku(kodeBuku);
        model.addObject("buku", buku);
        model.addObject("pengarangList", pengarangService.loadAll());

        String genres = buku.getKodeGenre();
        if (genres != null) {
            String[] genre = genres.split(",");

            for (int i = 0; i < genre.length; i++) {

                model.addObject(genre[i], genre[i]);
            }
        }

        return model;
    }

    @RequestMapping(value = "/bukuUpdate.html", method = RequestMethod.POST)
    public ModelAndView updateBuku(@ModelAttribute("buku") Buku buku, @RequestParam("kodePengarang") String kodePengarang,
            @RequestParam("fileGambar") MultipartFile fileGambar, HttpServletRequest request, HttpServletResponse response) throws ServiceException, IOException {

        String cover = Base64.encode(fileGambar.getBytes());

        bukuService.updateBuku(buku, kodePengarang, cover);

        return ViewHelper.redirectTo("bukuView.html");
    }

    @RequestMapping("/bukuDelete.html")
    public ModelAndView deleteBuku(HttpServletRequest request) {
        String idArray = request.getParameter("idArray");
        bukuService.deleteBuku(idArray);

        return ViewHelper.redirectTo("bukuView.html");
    }

    @RequestMapping("/mybooks.html")
    public ModelAndView detailBuku(HttpServletRequest request) {

        ModelAndView model = new ModelAndView("mybooks");
        String kodeUser = (String) request.getSession(false).getAttribute("kodeUser");

        List<BukuUser> bukuUserList = bukuService.loadUserBuku(kodeUser);

        model.addObject("bukuUserList", bukuUserList);
        model.addObject("userName", request.getSession(false).getAttribute("name"));
        return model;
    }

    @RequestMapping("/addToShelf.html")
    public ModelAndView addToShelf(HttpServletRequest request) throws DataAdditionException {

        String kodeUser = (String) request.getSession(false).getAttribute("kodeUser");
        String kodeBuku = request.getParameter("kodeBuku");

        bukuService.addToShelf(kodeUser, kodeBuku);

        return ViewHelper.redirectTo("recommendations.html");
    }

    @RequestMapping("/addReview.html")
    public ModelAndView addReview(HttpServletRequest request) throws DataAdditionException {

        String kodeUser = (String) request.getSession(false).getAttribute("kodeUser");
        String kodeBuku = request.getParameter("kodeBuku");

        bukuService.addToShelf(kodeUser, kodeBuku);


        return ViewHelper.redirectTo("detailBooks.html?kodBuku=" + kodeBuku);
    }

    @RequestMapping("/recommendations.html")
    public ModelAndView recommendations(HttpServletRequest request) {

        ModelAndView model = new ModelAndView("recommendations");

        User user = userService.loadUser((String) request.getSession(false).getAttribute("kodeUser"));

        String genres = user.getInterestedGenre();
        if (genres != null) {
            String[] genre = genres.split(",");
            model.addObject("genreList", Arrays.asList(genre));


            for (int i = 0; i < genre.length; i++) {

                List<Buku> bukuList = bukuService.getBukuByGenre(genre[i]);

                model.addObject(genre[i], bukuList);
            }
        }

        return model;
    }

    @RequestMapping("/editRecommendations.html")
    public ModelAndView editRecommendations(HttpServletRequest request) {

        ModelAndView model = new ModelAndView("editRecommendations");

        User user = userService.loadUser((String) request.getSession(false).getAttribute("kodeUser"));

        String genres = user.getInterestedGenre();
        if (genres != null) {
            String[] genre = genres.split(",");

            for (int i = 0; i < genre.length; i++) {

                model.addObject(genre[i], genre[i]);
            }
        }

        return model;
    }

    @RequestMapping("/detailBooks.html")
    public ModelAndView detailBooks(HttpServletRequest request) {

        String kodeBuku = request.getParameter("kodeBuku");
        String kodeUser = (String) request.getSession(false).getAttribute("kodeUser");

        ModelAndView model = new ModelAndView("detailBooks");

        BukuUser bukuUser = bukuService.loadBukuUser(kodeUser, kodeBuku);
        List<BukuUser> reviewList = bukuService.loadReview(kodeBuku, kodeUser);

        model.addObject("buku", bukuService.detailBuku(kodeBuku));
        model.addObject("bukuUser", bukuUser);
        model.addObject("reviewList", reviewList);

        return model;

    }

    @RequestMapping("/deleteMyBooks.html")
    public ModelAndView deleteMyBooks(HttpServletRequest request) throws DataDeletionException {

        String kodeBuku = request.getParameter("kodeBuku");
        String kodeUser = (String) request.getSession(false).getAttribute("kodeUser");

        bukuService.deleteMyBooks(kodeUser, kodeBuku);

        return ViewHelper.redirectTo("mybooks.html");
    }

    @RequestMapping("/rateBook.html")
    public ModelAndView rateBook(HttpServletRequest request) throws DataAdditionException {

        String kodeBuku = request.getParameter("kodeBuku");
        String rate = request.getParameter("rate");
        String kodeUser = (String) request.getSession(false).getAttribute("kodeUser");

        bukuService.rateBook(kodeUser, kodeBuku, Integer.valueOf(rate));

        return ViewHelper.redirectTo("mybooks.html");
    }

    @RequestMapping("/editReview.html")
    public ModelAndView editReview(HttpServletRequest request) {

        ModelAndView model = new ModelAndView("editReview");

        String kodeBuku = request.getParameter("kodeBuku");
        String kodeUser = (String) request.getSession(false).getAttribute("kodeUser");

        BukuUser bukuUser = bukuService.loadBukuUser(kodeUser, kodeBuku);

        model.addObject("bukuUser", bukuUser);

        return model;
    }

    @RequestMapping("/saveReview.html")
    public ModelAndView saveReview(HttpServletRequest request) throws DataModificationException {

        String kodeBuku = request.getParameter("kodeBuku");
        String kodeUser = (String) request.getSession(false).getAttribute("kodeUser");
        String review = request.getParameter("review");

        BukuUser bukuUser = bukuService.loadBukuUser(kodeUser, kodeBuku);
        bukuUser.setReviewBuku(review);
        bukuUser.setTanggalReviewBuku(new Date());

        bukuService.updateBukuUser(bukuUser);

        return ViewHelper.redirectTo("detailBooks.html?kodeBuku=" + kodeBuku);
    }

    @RequestMapping("/searchBook.html")
    public ModelAndView searchBook(HttpServletRequest request) {

        String page = request.getParameter("page");
        String mode = "search";

        if ((page == null) || page.equals("")) {
            page = "1";
        }

        BukuFilterCriteria filter = new BukuFilterCriteria();
        filter.setPage(Integer.valueOf(page));
        filter.setMax(10);

        String dataSearch = null;
        if (mode.equals("search")) {
            dataSearch = request.getParameter("query");
            if (!dataSearch.equals("")) {
                filter.setDataSearch(dataSearch);
            }
        }

        BukuDto bukuDto = bukuService.filterBuku(filter);

        ModelAndView model = new ModelAndView("searchBook");
        model.addObject("data", bukuDto);
        //model.addObject("dataSearch", dataSearch);

        return model;
    }
//    @RequestMapping(value = "/print/cetakbarcodepengesahanbynospd/{ispd}", method = RequestMethod.POST)
//    public void cetakpengesahan(final HttpServletResponse response, @PathVariable String ispd) {
//
//        response.setContentType("image/jpeg");
//
//        String pathToWeb = getServletContext().getRealPath(File.separator);
//        File f = new File(pathToWeb + "avajavalogo.jpg");
//        BufferedImage bi = ImageIO.read(f);
//        OutputStream out = response.getOutputStream();
//        ImageIO.write(bi, "jpg", out);
//        out.close();
//
//    }
}
